package orderProcessingProcess.server;

import javax.ws.rs.core.Response;
import javax.ws.rs.WebApplicationException;

import org.apache.cxf.jaxrs.client.JAXRSClientFactory;

import orderProcessingProcess.server.CustomerManagementService;
import orderProcessingProcess.exceptions.faults.UnknownCustomerFault;
import orderProcessingProcess.exceptions.faults.CustomerNotUpdatedFault;
import orderProcessingProcess.exceptions.faults.CustomerNotAddedFault;
import orderProcessingProcess.model.Customer;

public class CustomerManagementServiceSOAPImpl implements CustomerManagementServiceSOAP {
	private CustomerManagementService customers;
	
	public CustomerManagementServiceSOAPImpl() {
		customers = JAXRSClientFactory.create("http://localhost:8085/customers", CustomerManagementService.class);		
	}
	
	public void addCustomer(Customer newCustomer) throws CustomerNotAddedFault {
		Response r;
		try {
			r = customers.addCustomer(newCustomer);
		} catch (WebApplicationException wae) {
			r = wae.getResponse();
		}
		if (r.getStatus() != Response.Status.OK.getStatusCode())
		    throw new CustomerNotAddedFault("[CustomerManagementServiceSOAP] New Customer could not be added");
	}

	public void deleteCustomer(String id) throws UnknownCustomerFault {
		Response r;
		try {
			r = customers.deleteCustomer(id);
		} catch (WebApplicationException wae) {
			r = wae.getResponse();
		}
		if (r.getStatus() == Response.Status.NOT_FOUND.getStatusCode())
			throw new UnknownCustomerFault("[CustomerManagementServiceSOAP] not found");
	}

	public Customer getCustomer(String id) throws UnknownCustomerFault {
		try {
			Customer c = customers.getCustomer(id);
			if (c != null)
				return c;
			else
				throw new UnknownCustomerFault("[CustomerManagementServiceSOAP] not found");
		} catch (WebApplicationException wae) {
			if (wae.getResponse().getStatus() == Response.Status.NOT_FOUND.getStatusCode())
				throw new UnknownCustomerFault("[CustomerManagementServiceSOAP] not found");
		}
		return null;
	}

	public void updateCustomer(String id, Customer newCustomer) throws UnknownCustomerFault, CustomerNotUpdatedFault {
		Response r;
		try {
			r = customers.updateCustomer(id, newCustomer);
		} catch (WebApplicationException wae) {
			r = wae.getResponse();
		}

		if (r.getStatus() == Response.Status.NOT_FOUND.getStatusCode())
			throw new UnknownCustomerFault("[CustomerManagementServiceSOAP] not found");
		else if (r.getStatus() == Response.Status.NOT_MODIFIED.getStatusCode())
			throw new CustomerNotUpdatedFault("[CustomerManagementServiceSOAP] Customer could not be updated");
	}

}
